<?php

declare(strict_types=1);

namespace App\Common\Exception\Handler;

use App\Helpers\Helper;
use Donjan\Permission\Exceptions\UnauthorizedException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationExceptionHandler;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class UnauthorizedExceptionHandler extends ValidationExceptionHandler
{

    /**
     * @Inject
     * @var Helper
     */
    protected $helper;

    public function handle(Throwable $throwable, ResponseInterface $response)
    {

        $this->stopPropagation();
        $result = $this->helper->error($throwable->getCode(), $throwable->getMessage());
        return $response->withStatus($throwable->getCode())
            ->withAddedHeader('content-type', 'application/json')
            ->withBody(new SwooleStream($this->helper->jsonEncode($result)));
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof UnauthorizedException;
    }
}
